package com.ruben;

import cn.hutool.core.bean.BeanUtil;
import com.ruben.pojo.User;
import com.ruben.pojo.po.UserPO;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.cglib.beans.BeanCopier;

import java.math.BigDecimal;
import java.util.stream.Stream;

/**
 * 我还没有写描述
 *
 * @author <achao1441470436@gmail.com>
 * @date 2021/4/18 0018 14:43
 */
public class CopyDemo {
    public static void main(String[] args) {
        BeanCopier beanCopier = BeanCopier.create(Monkey.class, Cat.class, false);
        Monkey monkey = Monkey.builder().name("ruben").age(12).build();
        Cat cat = Cat.builder().build();
        beanCopier.copy(monkey, cat, null);
        System.out.println(cat);
    }

    @Data
    @Builder
    @EqualsAndHashCode
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Monkey {
        private String name;
        private Integer age;
    }

    @Data
    @Builder
    @EqualsAndHashCode
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public static class Cat {
        private String name;
        private Integer age;
    }

    private static void whichFast() {
        User user = User.builder().username("asdadad").password("asdad").build();
        for (int i = 0; i < 100; i++) {
            beanCopier(user);
            beanUtil(user);
        }
        Stream.generate(() -> beanUtil(user)).limit(200).reduce(BigDecimal::add).ifPresent(System.out::println);
        Stream.generate(() -> beanCopier(user)).limit(200).reduce(BigDecimal::add).ifPresent(System.out::println);
    }

    public static BigDecimal beanUtil(User user) {
        long start = System.nanoTime();
        for (int i = 0; i < 400; i++) {
            UserPO userPO = UserPO.builder().build();
            BeanUtil.copyProperties(user, userPO);
        }
        long end = System.nanoTime();
        double result = (end - start) / (1000.0 * 1000.0);
//        System.out.println("beanUtil：" + result + "ms");
        return BigDecimal.valueOf(result);
    }

    public static BigDecimal beanCopier(User user) {
        long start = System.nanoTime();
        for (int i = 0; i < 400; i++) {
            UserPO userPO = UserPO.builder().build();
            BeanCopier copier = BeanCopier.create(User.class, UserPO.class, false);
            copier.copy(user, userPO, null);
        }
        long end = System.nanoTime();
        double result = (end - start) / (1000.0 * 1000.0);
//        System.out.println("beanCopier：" + result + "ms");
        return BigDecimal.valueOf(result);
    }
}
